<template>
  <el-form
    size="large"
    :model="state.ruleForm"
    :rules="rules"
    ref="loginFormRef"
    class="login-content-form"
    v-if="loginState == 0"
  >
    <el-form-item class="login-animation1">
      <div>
        <div style="font-size: 18px; font-weight: 500">账号密码登录</div>
        <div style="font-size: 12px; font-weight: 400; line-height: 12px">
          账号密码登录仅支持微信小程序，企微和钉钉可扫码登录
        </div>
      </div>
    </el-form-item>
    <el-form-item class="login-animation1" prop="userAccount">
      <el-input
        text
        :placeholder="$t('message.account.accountPlaceholder1')"
        v-model="state.ruleForm.userAccount"
        clearable
        autocomplete="off"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><ele-User /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item class="login-animation2" prop="userPwd">
      <el-input
        :type="state.isShowPassword ? 'text' : 'password'"
        :placeholder="$t('message.account.accountPlaceholder2')"
        v-model="state.ruleForm.userPwd"
        autocomplete="off"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><ele-Unlock /></el-icon>
        </template>
        <template #suffix>
          <i
            class="iconfont el-input__icon login-content-password"
            :class="
              state.isShowPassword ? 'icon-xianshimima' : 'icon-yincangmima'
            "
            @click="state.isShowPassword = !state.isShowPassword"
          >
          </i>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item class="login-animation3">
      <el-col :span="15">
        <el-checkbox v-model="state.isRememberPwd" size="large">{{
          $t('message.account.accountSave')
        }}</el-checkbox>
      </el-col>
      <el-col :span="4"></el-col>
      <el-col :span="5">
        <el-button
          type="info"
          link
          @click="forgetPwd(state.ruleForm.userAccount)"
          >{{ $t('message.account.accountForget') }}</el-button
        >
      </el-col>
    </el-form-item>
    <el-form-item class="login-animation4">
      <div style="width: 100%; display: flex; justify-content: space-around">
        <el-button
          type="primary"
          text
          bg
          class="login-content-submit"
          v-waves
          @click="goRegister(2)"
          :loading="state.loading.signIn"
        >
          <span class="login-content-submit__txt1"> 申请注册 </span>
        </el-button>
        <el-button
          type="primary"
          class="login-content-submit"
          v-waves
          @click="onSignIn()"
          :loading="state.loading.signIn"
        >
          <span class="login-content-submit__txt">{{
            $t('message.account.accountBtnText')
          }}</span>
        </el-button>
      </div>
    </el-form-item>
    <el-form-item class="login-animation4">
      <div style="width: 100%">
        <el-divider content-position="center"
          >扫码登录，微信、企微、钉钉数据不互通</el-divider
        >
      </div>
    </el-form-item>
    <el-form-item class="login-animation5">
      <div class="login-content-copyright">
        <!-- {{ $t('message.account.copyRight') }} -->
        <img src="../../../assets/WeChatLogin.png" @click="wxLogin(1)" />
        <img src="../../../assets/qiyeweixinLogin.png" @click="wxLogin(2)" />
        <img src="../../../assets/dingdingLogin.png" @click="wxLogin(3)" />
      </div>
    </el-form-item>
  </el-form>
  <div v-else-if="loginState == 1">
    <el-form-item class="login-animation1">
      <div style="width: 100%; cursor: pointer" @click="loginBack()">
        <img style="width: 24px" src="../../../assets/backImg.png" alt="" />
      </div>
    </el-form-item>
    <div style="display: flex; justify-content: center">
      <wxlogin
        :appid="wxObj.appid"
        :scope="'snsapi_login'"
        :theme="'black'"
        :redirect_uri="wxObj.redirect_uri"
        :state="wxObj.state"
      >
      </wxlogin>
    </div>
  </div>
  <div v-else-if="loginState == 2">
    <el-form
      :model="state.registerForm"
      :rules="registerRules"
      ref="registerFormRef"
    >
      <el-form-item class="login-animation1">
        <div style="width: 100%">
          <div class="registerTitle">
            <div class="registerTitle__back" @click="loginBack()">
              <img
                style="width: 24px"
                src="../../../assets/backImg.png"
                alt=""
              />
            </div>
            <div class="registerTitle__wxInfo" v-if="props.registerType">
              <img :src="props.portrait" alt="" />
              <div>{{ props.realName }}</div>
            </div>
          </div>
          <div class="wxUserInfo" v-if="props.registerType">
            <div style="font-size: 32px; font-weight: 500">试用账号注册</div>
            <div
              style="
                font-size: 12px;
                font-weight: 400;
                color: rgba(140, 140, 140, 1);
              "
            >
              没有账号，注册账号信息填写
            </div>
          </div>
          <div class="wxUserInfo" v-else>
            <div style="font-size: 32px; font-weight: 500">试用申请</div>
            <div
              style="
                font-size: 12px;
                font-weight: 400;
                color: rgba(140, 140, 140, 1);
              "
            >
              微信小程序注册信息填写，企微及钉钉可扫码直接注册
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item class="login-animation1" prop="adminName">
        <el-input
          text
          placeholder="请输入姓名"
          v-model="state.registerForm.adminName"
          clearable
          autocomplete="off"
        >
        </el-input>
      </el-form-item>
      <el-form-item class="login-animation1" prop="companyName">
        <el-input
          text
          placeholder="请输入公司"
          v-model="state.registerForm.companyName"
          clearable
          autocomplete="off"
        >
        </el-input>
      </el-form-item>
      <el-form-item class="login-animation1" prop="adminPhone">
        <el-input
          text
          placeholder="请输入手机号"
          v-model="state.registerForm.adminPhone"
          clearable
          autocomplete="off"
        >
        </el-input>
      </el-form-item>
      <el-form-item class="login-animation1" prop="smsCode">
        <el-input
          v-model="state.registerForm.smsCode"
          placeholder="请输入验证码"
          style="width: 75%"
        />
        <el-button
          type="primary"
          style="width: 25%"
          @click="getCode"
          :disabled="!getCodeFlag"
          >{{
            getCodeFlag ? '获取验证码' : '已发送(' + codeNum + ')'
          }}</el-button
        >
      </el-form-item>
      <el-form-item class="login-animation1" prop="adminPwd">
        <el-input
          text
          placeholder="请输入密码"
          v-model="state.registerForm.adminPwd"
          clearable
          autocomplete="off"
        >
        </el-input>
      </el-form-item>
      <el-form-item style="margin: 0 !important; line-height: 20px !important">
        <el-checkbox v-model="registerCheckBox" size="large" />
        <span>
          已阅读并同意
          <span
            style="color: var(--el-color-primary); cursor: pointer"
            @click="goHtml(1)"
            >《隐私政策》</span
          >
          和
          <span
            style="color: var(--el-color-primary); cursor: pointer"
            @click="goHtml(2)"
            >《用户协议》</span
          >
        </span>
      </el-form-item>
      <el-form-item class="login-animation1">
        <el-button
          type="primary"
          class="login-content-submit"
          style="width: 100%"
          v-waves
          @click="onRegister()"
          :loading="state.loading.signIn"
        >
          <span class="login-content-submit__txt"> 注册 </span>
        </el-button>
        <div style="width: 100%; text-align: center">
          已有账号？
          <span
            style="color: var(--el-color-primary); cursor: pointer"
            @click="goRegister(0)"
            >直接登录</span
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
  <div v-else-if="loginState == 3">
    <el-form :model="state.bandForm" :rules="bandFormRules" ref="bandFormRef">
      <el-form-item class="login-animation1">
        <div style="width: 100%">
          <div class="registerTitle">
            <div class="registerTitle__back" @click="loginBack()">
              <img
                style="width: 24px"
                src="../../../assets/backImg.png"
                alt=""
              />
            </div>
            <div class="registerTitle__wxInfo">
              <img :src="props.portrait" alt="" />
              <div>{{ props.realName }}</div>
            </div>
          </div>
          <div class="wxUserInfo">
            <div style="font-size: 32px; font-weight: 500">绑定账号</div>
            <div
              style="
                font-size: 12px;
                font-weight: 400;
                color: rgba(140, 140, 140, 1);
              "
            >
              若已有账号，请绑定账号信息
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item class="login-animation1" prop="userAccount">
        <el-input
          text
          placeholder="请输入手机号"
          v-model="state.bandForm.userAccount"
          clearable
          autocomplete="off"
        >
        </el-input>
      </el-form-item>
      <el-form-item class="login-animation1" prop="userPwd">
        <el-input
          text
          placeholder="请输入密码"
          v-model="state.bandForm.userPwd"
          clearable
          autocomplete="off"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <div
          style="
            width: 100%;
            color: rgba(140, 140, 140, 1);
            text-align: right;
            cursor: pointer;
          "
          @click="forgetPwd(state.bandForm.userAccount)"
        >
          忘记密码
        </div>
      </el-form-item>
      <el-form-item class="login-animation1">
        <el-button
          type="primary"
          class="login-content-submit"
          style="width: 100%"
          v-waves
          @click="onSignIn2()"
          :loading="state.loading.signIn"
        >
          <span class="login-content-submit__txt"> 登录 </span>
        </el-button>
        <div style="width: 100%; text-align: center">
          <span style="color: rgba(140, 140, 140, 1)">没有账号？</span>
          <span
            style="color: var(--el-color-primary); cursor: pointer"
            @click="goRegister(2)"
            >直接注册</span
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
  <div v-show="loginState == 4">
    <el-form-item class="login-animation1">
      <img
        @click="goBack()"
        style="width: 24px; cursor: pointer"
        src="../../../assets/backImg.png"
        alt=""
      />
    </el-form-item>
    <el-form-item>
      <div id="qiyeLogin"></div>
    </el-form-item>
  </div>
  <ChangePwd
    :dialog="dialogPwd"
    :type="'login'"
    :tokenPwd="tokenPwd"
    @updatePwd="updatePwd"
  ></ChangePwd>
</template>

<script setup lang="ts" name="loginAccount">
import { reactive, computed, ref, defineAsyncComponent, onMounted } from 'vue'
import { FormInstance, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import Cookies from 'js-cookie'
import { storeToRefs } from 'pinia'
import { Md5 } from 'ts-md5/dist/md5'
import { useThemeConfig } from '/@/stores/themeConfig'
import { useChangeColor } from '/@/utils/theme'
import { initFrontEndControlRoutes } from '/@/router/frontEnd'
import { initBackEndControlRoutes } from '/@/router/backEnd'
import { Session } from '/@/utils/storage'
import { formatAxis } from '/@/utils/formatTime'
import { NextLoading } from '/@/utils/loading'
import { signIn, bindUserApi, webThirdLoginApi } from '/@/api/login/index'
import { Local } from '/@/utils/storage'
import { getCompanyInfo } from '/@/api/setting/enterpriseInfo'
import { useQiyeInfo } from '/@/stores/qiyeInfo'
import { useUserInfo } from '/@/stores/userInfo'
import {
  getMenuListByRole,
  getWebThirdConfigApi,
  sendSmsCode,
  verifySmsCodeApi,
  applyTrialApi
} from '/@/api/login'
import { getLoginUserInfoApi } from '/@/api/user'
import wxlogin from 'vue-wxlogin'
import * as ww from '@wecom/jssdk'
const menuList = Session.get('menu')
const stores = useQiyeInfo()
const stores2 = useUserInfo()
const ChangePwd = defineAsyncComponent(
  () => import('/@/layout/navBars/breadcrumb/ChangePwd.vue')
)
const LoginQR = defineAsyncComponent(() => import('../../loginQR/index.vue'))
const props = defineProps({
  accountPhone: String as any,
  accountPWD: String as any,
  loginState: Number as any,
  realName: String as any,
  portrait: String as any,
  thirdId: String as any,
  registerType: Boolean as any
})
const emit = defineEmits(['forgetPwd', 'goRegister'])
// 定义变量内容
const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const storesThemeConfig = useThemeConfig()
const { themeConfig } = storeToRefs(storesThemeConfig)
const { getLightColor } = useChangeColor()
const loginFormRef = ref<FormInstance>()
const bandFormRef = ref<FormInstance>()
let dialogPwd = ref<boolean>(false)
const registerCheckBox = ref<boolean>(false)
let tokenPwd = ref<string>('')
const state = reactive({
  isShowPassword: false,
  ruleForm: {
    userAccount: '',
    userPwd: ''
  },
  bandForm: {
    userAccount: '',
    userPwd: '',
    thirdId: props.thirdId,
    bindType: 1
  },
  registerForm: {
    adminName: '',
    companyName: '',
    adminPhone: '',
    smsCode: '',
    adminPwd: '',
    portrait: props.portrait,
    thirdId: props.thirdId,
    trySource: 3
  },
  loading: {
    signIn: false
  },
  isRememberPwd: false,
  registerType: 1 //注册类型 1: 直接注册, 2:微信扫码注册
})

const rules = reactive({
  userAccount: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入您的账号'
    },
    {
      pattern: /^[a-zA-Z0-9]{6,11}$/,
      message: '请输入由数字/字母组成的6-11位账号',
      trigger: 'blur'
    }
  ],
  userPwd: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入您的登录密码'
    }
  ]
})
const bandFormRules = reactive({
  userAccount: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入您的账号'
    }
  ],
  userPwd: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入您的登录密码'
    }
  ]
})
const registerRules = reactive({
  adminName: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入您的姓名'
    }
  ],
  adminPhone: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入您的账号'
    }
  ],
  companyName: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入您的公司名称'
    }
  ],
  adminPwd: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入您的密码'
    }
  ]
})

onMounted(async () => {
  if (Local.get('saveaccount')) {
    let obj = JSON.parse(Local.get('saveaccount'))
    if (obj.checked) {
      state.isRememberPwd = true
      state.ruleForm.userAccount = obj.login.userLogin
      state.ruleForm.userPwd = obj.login.password
    }
  }
  if (props.accountPhone != '') {
    state.ruleForm.userAccount = props.accountPhone
    state.ruleForm.userPwd = props.accountPWD
  }
})

// 时间获取
const currentTime = computed(() => {
  return formatAxis(new Date())
})

const changeColor = (c: any) => {
  themeConfig.value.primary = c
  document.documentElement.style.setProperty('--el-color-primary', c)

  // 颜色变浅
  for (let i = 1; i <= 9; i++) {
    document.documentElement.style.setProperty(
      `--el-color-primary-light-${i}`,
      `${getLightColor(c, i / 10)}`
    )
  }
}

const updatePwd = (val: any) => {
  ElMessageBox.confirm('密码修改成功,是否直接登录系统?', '提示', {
    confirmButtonText: '直接登录',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      state.ruleForm.userPwd = val
      dialogPwd.value = !dialogPwd.value
      onSignIn()
    })
    .catch(() => {
      state.ruleForm.userPwd = ''
      dialogPwd.value = !dialogPwd.value
      Session.clear()
      window.location.reload()
    })
}

//微信登录
const wxObj = ref({
  appid: '',
  redirect_uri: '',
  state: ''
})
const wxLogin = async (val: any) => {
  let res = await getWebThirdConfigApi(val)
  if (res.code == 0) {
    console.log(res.data)
    wxObj.value.appid = res.data.appid
    wxObj.value.state = res.data.state
    wxObj.value.redirect_uri = encodeURIComponent(res.data.redirect_uri)
    if (val == 1) {
      goRegister(1)
    } else if (val == 2) {
      wwLogin(res.data)
    } else {
      ElMessage.warning('钉钉登录暂未开放...')
    }
  }
}

//企业微信登录
// 初始化
const qywxLogin: any = ref(null)
const wwLogin = (wxObj: any) => {
  qywxLogin.value = ww.createWWLoginPanel({
    el: '#qiyeLogin',
    params: {
      login_type: ww.WWLoginType.serviceApp,
      appid: wxObj.appid,
      redirect_uri: wxObj.redirect_uri,
      state: wxObj.state,
      redirect_type: ww.WWLoginRedirectType.callback
    },
    onCheckWeComLogin({ isWeComLogin }) {
      console.log(isWeComLogin)
    },
    async onLoginSuccess({ code }) {
      if (code != '') {
        let params = {
          bindType: 2,
          code: code,
          state: wxObj.state
        }
        let res = await webThirdLoginApi(params)
        if (res.code == 0) {
          login(res)
        }
      }
    },
    onLoginFail(err) {
      console.log(err)
    }
  })
  goRegister(4)
}

const goBack = () => {
  qywxLogin.value.unmount()
  goRegister(0)
}

//申请注册
const goRegister = (val: any) => {
  emit('goRegister', val)
}

// 登录
const onSignIn = async () => {
  if (!loginFormRef.value) return
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      state.loading.signIn = true
      const params = {
        userAccount: state.ruleForm.userAccount,
        userPwd: Md5.hashStr(state.ruleForm.userPwd)
      }
      let res = await signIn(params)
      if (res?.code === 0) {
        // 存储 token 到浏览器缓存
        if (res.data.token == '') {
          if (res.data.surplusCount == 0) {
            ElMessageBox.confirm(
              '密码已连续输错5次，账号已被锁定，请点击忘记密码找回或者24小时后重试',
              '提示',
              {
                confirmButtonText: '忘记密码',
                cancelButtonText: '知道了',
                type: 'warning'
              }
            )
              .then(() => {
                forgetPwd(state.ruleForm.userAccount)
              })
              .catch(() => {
                state.loading.signIn = false
              })
          } else {
            ElMessageBox.confirm(
              `密码错误，您今天还剩${res.data.surplusCount}次机会，请重新输入`,
              '提示',
              {
                confirmButtonText: '忘记密码',
                cancelButtonText: '知道了',
                type: 'warning'
              }
            )
              .then(() => {
                forgetPwd(state.ruleForm.userAccount)
              })
              .catch(() => {
                state.loading.signIn = false
              })
          }
        } else {
          if (res.data.modifyPwdFlag == 0) {
            tokenPwd.value = res.data.token
            dialogPwd.value = !dialogPwd.value
            state.loading.signIn = false
          } else {
            Session.set('token', res.data.token)
            Session.set('shebei', res.data)
            getCompanyInfo().then((r) => {
              if (r.code == 0) {
                Session.set('qiye', r.data)
                stores.setQiyeInfos()
              }
            })
            getLoginUserInfoApi().then((res) => {
              if (res.code == 0) {
                Session.remove('shebei')
                Session.set('shebei', res.data)
                stores2.setUserInfos()
              }
            })
            //localStorage 存储记住密码状态 1记住 2不记住
            if (state.isRememberPwd) {
              let loginInfo = {
                checked: state.isRememberPwd,
                login: {
                  userLogin: state.ruleForm.userAccount,
                  password: state.ruleForm.userPwd
                }
              }
              Local.set('saveaccount', JSON.stringify(loginInfo))
            } else {
              if (Local.get('saveaccount')) {
                Local.remove('saveaccount')
              }
            }

            let myThemeConfig = Local.get('themeConfig')
            // 字号前后端不一致  换
            let size =
              myThemeConfig.globalFontSize == '14px'
                ? 1
                : myThemeConfig.globalFontSize == '16px'
                ? 2
                : myThemeConfig.globalFontSize == '18px'
                ? 3
                : 1
            if (size != res.data.wordSize) {
              Local.remove('themeConfig')
              themeConfig.value.globalFontSize =
                res.data.wordSize == 1
                  ? '14px'
                  : res.data.wordSize == 2
                  ? '16px'
                  : res.data.wordSize == 3
                  ? '18px'
                  : '14px'
              Local.set('themeConfig', themeConfig.value)
              document.documentElement.style.setProperty(
                '--el-font-size-base',
                themeConfig.value.globalFontSize
              )
              if (size == 1) {
                document.documentElement.style.setProperty(
                  '--next-font-size22',
                  '22px'
                )
                document.documentElement.style.setProperty(
                  '--next-font-size20',
                  '20px'
                )
                document.documentElement.style.setProperty(
                  '--next-font-size18',
                  '18px'
                )
              } else if (size == 2) {
                document.documentElement.style.setProperty(
                  '--next-font-size22',
                  '24px'
                )
                document.documentElement.style.setProperty(
                  '--next-font-size20',
                  '22px'
                )
                document.documentElement.style.setProperty(
                  '--next-font-size18',
                  '20px'
                )
              } else if (size == 3) {
                document.documentElement.style.setProperty(
                  '--next-font-size22',
                  '26px'
                )
                document.documentElement.style.setProperty(
                  '--next-font-size20',
                  '24px'
                )
                document.documentElement.style.setProperty(
                  '--next-font-size18',
                  '22px'
                )
              }
            }
            let color =
              myThemeConfig.primary == '#02AD82'
                ? 1
                : myThemeConfig.primary == '#063C74'
                ? 2
                : myThemeConfig.primary == '#063C74'
                ? 3
                : 1
            if (color != res.data.themeColor) {
              Local.remove('themeConfig')
              themeConfig.value.primary =
                res.data.themeColor == 1
                  ? '#02AD82'
                  : res.data.themeColor == 2
                  ? '#063C74'
                  : res.data.themeColor == 3
                  ? '#514FC2'
                  : '#02AD82'
              Local.set('themeConfig', themeConfig.value)
              changeColor(themeConfig.value.primary)
            }
            Local.set(
              'themeConfigStyle',
              document.documentElement.style.cssText
            )

            if (!themeConfig.value.isRequestRoutes) {
              // 前端控制路由，2、请注意执行顺序
              const isNoPower = await initFrontEndControlRoutes()
              signInSuccess(isNoPower)
            } else {
              // 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
              // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
              const isNoPower = await initBackEndControlRoutes()
              // 执行完 initBackEndControlRoutes，再执行 signInSuccess
              signInSuccess(isNoPower)
            }
            state.loading.signIn = false
          }
        }
      } else {
        state.loading.signIn = false
      }
    } else {
      state.loading.signIn = false
      return false
    }
  })

  // 存储 token 到浏览器缓存
  // Session.set('token', Math.random().toString(36).substr(0))
  // 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
  // Cookies.set('userName', state.ruleForm.userAccount)
}
const onSignIn2 = async () => {
  if (!bandFormRef.value) return
  bandFormRef.value.validate(async (valid) => {
    if (valid) {
      state.loading.signIn = true
      const params = {
        userAccount: state.bandForm.userAccount,
        userPwd: Md5.hashStr(state.bandForm.userPwd),
        thirdId: state.bandForm.thirdId,
        bindType: state.bandForm.bindType
      }
      let res = await bindUserApi(params)
      if (res?.code === 0) {
        // 存储 token 到浏览器缓存
        if (res.data.token == '') {
          if (res.data.surplusCount == 0) {
            ElMessageBox.confirm(
              '密码已连续输错5次，账号已被锁定，请点击忘记密码找回或者24小时后重试',
              '提示',
              {
                confirmButtonText: '忘记密码',
                cancelButtonText: '知道了',
                type: 'warning'
              }
            )
              .then(() => {
                forgetPwd(state.bandForm.userAccount)
              })
              .catch(() => {
                state.loading.signIn = false
              })
          } else {
            ElMessageBox.confirm(
              `密码错误，您今天还剩${res.data.surplusCount}次机会，请重新输入`,
              '提示',
              {
                confirmButtonText: '忘记密码',
                cancelButtonText: '知道了',
                type: 'warning'
              }
            )
              .then(() => {
                forgetPwd(state.bandForm.userAccount)
              })
              .catch(() => {
                state.loading.signIn = false
              })
          }
        } else {
          if (res.data.modifyPwdFlag == 0) {
            tokenPwd.value = res.data.token
            dialogPwd.value = !dialogPwd.value
            state.loading.signIn = false
          } else {
            login(res)
          }
        }
      } else {
        state.loading.signIn = false
      }
    } else {
      state.loading.signIn = false
      return false
    }
  })

  // 存储 token 到浏览器缓存
  // Session.set('token', Math.random().toString(36).substr(0))
  // 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
  // Cookies.set('userName', state.ruleForm.userAccount)
}

const login = async (res: any) => {
  Session.set('token', res.data.token)
  Session.set('shebei', res.data)
  getCompanyInfo().then((r) => {
    if (r.code == 0) {
      Session.set('qiye', r.data)
      stores.setQiyeInfos()
    }
  })
  getLoginUserInfoApi().then((res) => {
    if (res.code == 0) {
      Session.remove('shebei')
      Session.set('shebei', res.data)
      stores2.setUserInfos()
    }
  })
  //localStorage 存储记住密码状态 1记住 2不记住
  if (state.isRememberPwd) {
    let loginInfo = {
      checked: state.isRememberPwd,
      login: {
        userLogin: state.ruleForm.userAccount,
        password: state.ruleForm.userPwd
      }
    }
    Local.set('saveaccount', JSON.stringify(loginInfo))
  } else {
    if (Local.get('saveaccount')) {
      Local.remove('saveaccount')
    }
  }

  let myThemeConfig = Local.get('themeConfig')
  // 字号前后端不一致  换
  let size =
    myThemeConfig.globalFontSize == '14px'
      ? 1
      : myThemeConfig.globalFontSize == '16px'
      ? 2
      : myThemeConfig.globalFontSize == '18px'
      ? 3
      : 1
  if (size != res.data.wordSize) {
    Local.remove('themeConfig')
    themeConfig.value.globalFontSize =
      res.data.wordSize == 1
        ? '14px'
        : res.data.wordSize == 2
        ? '16px'
        : res.data.wordSize == 3
        ? '18px'
        : '14px'
    Local.set('themeConfig', themeConfig.value)
    document.documentElement.style.setProperty(
      '--el-font-size-base',
      themeConfig.value.globalFontSize
    )
    if (size == 1) {
      document.documentElement.style.setProperty('--next-font-size22', '22px')
      document.documentElement.style.setProperty('--next-font-size20', '20px')
      document.documentElement.style.setProperty('--next-font-size18', '18px')
    } else if (size == 2) {
      document.documentElement.style.setProperty('--next-font-size22', '24px')
      document.documentElement.style.setProperty('--next-font-size20', '22px')
      document.documentElement.style.setProperty('--next-font-size18', '20px')
    } else if (size == 3) {
      document.documentElement.style.setProperty('--next-font-size22', '26px')
      document.documentElement.style.setProperty('--next-font-size20', '24px')
      document.documentElement.style.setProperty('--next-font-size18', '22px')
    }
  }
  let color =
    myThemeConfig.primary == '#02AD82'
      ? 1
      : myThemeConfig.primary == '#063C74'
      ? 2
      : myThemeConfig.primary == '#063C74'
      ? 3
      : 1
  if (color != res.data.themeColor) {
    Local.remove('themeConfig')
    themeConfig.value.primary =
      res.data.themeColor == 1
        ? '#02AD82'
        : res.data.themeColor == 2
        ? '#063C74'
        : res.data.themeColor == 3
        ? '#514FC2'
        : '#02AD82'
    Local.set('themeConfig', themeConfig.value)
    changeColor(themeConfig.value.primary)
  }
  Local.set('themeConfigStyle', document.documentElement.style.cssText)

  if (!themeConfig.value.isRequestRoutes) {
    // 前端控制路由，2、请注意执行顺序
    const isNoPower = await initFrontEndControlRoutes()
    signInSuccess(isNoPower)
  } else {
    // 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
    // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
    const isNoPower = await initBackEndControlRoutes()
    // 执行完 initBackEndControlRoutes，再执行 signInSuccess
    signInSuccess(isNoPower)
  }
  state.loading.signIn = false
}

// 登录成功后的跳转
const signInSuccess = async (isNoPower: boolean | undefined) => {
  console.log(isNoPower)
  if (isNoPower) {
    ElMessage.warning('抱歉，您没有登录权限')
    Session.clear()
  } else {
    // 初始化登录成功时间问候语
    let currentTimeInfo = currentTime.value
    // 登录成功，跳到转首页
    // 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
    const res = await getMenuListByRole()
    let path = res.data[0].menuUrl
    router.push({
      path: path
    })
    // 登录成功提示
    const signInText = t('message.signInText')
    ElMessage.success(`${currentTimeInfo}，${signInText}`)
    // 添加 loading，防止第一次进入界面时出现短暂空白
    NextLoading.start()
    NextLoading.done(4000)
    // }
  }
  state.loading.signIn = false
}

// 忘记密码
const forgetPwd = (userAccount: any) => {
  emit('forgetPwd', userAccount)
}

//注册账号
const onRegister = async () => {
  state.loading.signIn = true
  if (registerCheckBox.value) {
    let res = await verifySmsCodeApi({
      userAccount: state.registerForm.adminPhone,
      smsCode: state.registerForm.smsCode
    })
    if (res.code == 0) {
      let response = await applyTrialApi(state.registerForm)
      if (response.code == 0) {
        ElMessage.success('注册成功')
        state.ruleForm.userAccount = state.registerForm.adminPhone
        state.ruleForm.userPwd = state.registerForm.adminPwd
        // goRegister(0)
        login(response)
      } else {
        state.loading.signIn = false
      }
    } else {
      state.loading.signIn = false
    }
  } else {
    state.loading.signIn = false
    ElMessage.warning('请勾选隐私政策与用户协议!')
  }
}

const getCodeFlag = ref(true)
const codeNum = ref(60)
const timer = ref<any>(null)
const getCode = async () => {
  let res = await sendSmsCode({ userAccount: state.registerForm.adminPhone })
  if (res.code == 0) {
    ElMessage.success('已发送')
    getCodeFlag.value = false
    timer.value = setInterval(() => {
      if (codeNum.value > 0) {
        codeNum.value--
      } else {
        getCodeFlag.value = true
        codeNum.value = 60
        clearInterval(timer.value)
      }
    }, 1000)
  }
}

const loginBack = () => {
  goRegister(0)
}

const goHtml = (type: any) => {
  if (type == 1) {
    window.open('https://m.xiaobaixie.co/privacy_policy.html')
  } else {
    window.open('https://m.xiaobaixie.co/user_agreement.html')
  }
}

onMounted(() => {})
</script>

<style scoped lang="scss">
.login-content-form {
  margin-top: 20px;

  @for $i from 1 through 5 {
    .login-animation#{$i} {
      opacity: 0;
      animation-name: error-num;
      animation-duration: 0.5s;
      animation-fill-mode: forwards;
      animation-delay: calc($i/10) + s;
    }
  }

  .login-content-password {
    display: inline-block;
    width: 20px;
    cursor: pointer;

    &:hover {
      color: #909399;
    }
  }

  .login-content-code {
    width: 100%;
    padding: 0;
    font-weight: bold;
    letter-spacing: 5px;
  }
}

.login-content-copyright {
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #8c8c8c;
  display: flex;
  justify-content: space-evenly;
  > img {
    width: 40px;
    cursor: pointer;
  }
}

.login-content-form .el-button {
  margin-left: 0;
}
.login-content-form .el-checkbox {
  margin-right: 5px;
}

.registerTitle {
  width: 100%;
  line-height: 0;
  display: flex;
  align-items: center;

  &__back {
    cursor: pointer;
    margin-right: 10px;
    // margin-bottom: 20px;
    line-height: 40px;
  }

  &__wxInfo {
    display: flex;
    align-items: center;

    > img {
      width: 40px;
      height: 40px;
      border-radius: 40px;
      margin-right: 10px;
    }
  }
}

.wxUserInfo {
  width: 100%;
  text-align: center;
}
.login-content-submit {
  width: 168px;
  letter-spacing: 2px;
  font-weight: 300;
  margin-top: 15px;
  border-radius: 83px;

  &__txt {
    font-size: 20px;
    font-weight: 700;
    color: white;
  }

  &__txt1 {
    font-size: 20px;
    font-weight: 700;
    color: var(--el-color-primary);
  }
}
</style>
<style lang="scss">
.login-content-form .el-divider__text {
  width: 300px;
}

.login-content-form .el-button.is-text:not(.is-disabled).is-has-bg {
  border: 1px solid var(--el-color-primary);
}
</style>
